package com.atguigu.lease.web.admin.service.impl;
import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.CircleCaptcha;
import cn.hutool.crypto.digest.DigestUtil;
import com.atguigu.lease.common.exception.LeaseException;
import com.atguigu.lease.common.result.ResultCodeEnum;
import com.atguigu.lease.common.utils.JwtUtils;
import com.atguigu.lease.model.entity.SystemUser;
import com.atguigu.lease.model.enums.BaseStatus;
import com.atguigu.lease.web.admin.mapper.SystemUserMapper;
import com.atguigu.lease.web.admin.service.LoginService;
import com.atguigu.lease.web.admin.vo.login.CaptchaVo;
import com.atguigu.lease.web.admin.vo.login.LoginVo;
import com.atguigu.lease.web.admin.vo.system.user.SystemUserInfoVo;
import com.atguigu.lease.web.admin.vo.system.user.SystemUserItemVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.SneakyThrows;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class LoginServiceImpl implements LoginService {
    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Autowired
    private SystemUserMapper systemUserMapper;

    @Override
    public CaptchaVo getCaptcha() {

        //使用hutool工具包生成验证码图片
        CircleCaptcha circleCaptcha = CaptchaUtil.createCircleCaptcha(150,50,5,20);
        //获取验证码字符串
        String code = circleCaptcha.getCode();
        //获取 验证码image
        String imageBase64 = circleCaptcha.getImageBase64();
        //生成验证码图片的key
        String key = UUID.randomUUID().toString().replace("-", "");
        //将验证码保存在Redis中
        redisTemplate.opsForValue().set(key,code,60, TimeUnit.MINUTES);
        //使用hutool工具包生成验证码图片
//        LineCaptcha lineCaptcha = new LineCaptcha(150,50,5,20);
//        //获取验证码字符串
//        String code = lineCaptcha.getCode();
//        //获取 验证码image
//        String imageBase64 = lineCaptcha.getImageBase64();
//        //生成验证码图片的key
//        String key = UUID.randomUUID().toString().replace("-", "");
//        //将验证码保存在Redis中
//        redisTemplate.opsForValue().set(key,code,10,TimeUnit.MINUTES);

        return new CaptchaVo(imageBase64,key);
    }

    @Override
    public String login(LoginVo loginVo){
        //判断是否输入验证码
        if (loginVo.getCaptchaCode() == null){
             throw new LeaseException(ResultCodeEnum.APP_LOGIN_CODE_EMPTY);
        //根据用户输入的验证码查询Redis保存的验证码，如果结果为空，则返回验证码已过期
        } else if (redisTemplate.opsForValue().get(loginVo.getCaptchaKey()) == null){
            throw new LeaseException(ResultCodeEnum.ADMIN_CAPTCHA_CODE_EXPIRED);
        //如果用户输入的验证码跟Redis中的验证码不一致，则返回验证码错误
        } else if (!loginVo.getCaptchaCode().equalsIgnoreCase(redisTemplate.opsForValue().get(loginVo.getCaptchaKey()))) {
            throw new LeaseException(ResultCodeEnum.ADMIN_CAPTCHA_CODE_ERROR);
        }

        //验证用户名
        LambdaQueryWrapper<SystemUser> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(SystemUser::getUsername,loginVo.getUsername());
        SystemUser systemUser = systemUserMapper.selectOne(lambdaQueryWrapper);
        if (systemUser == null){
            throw new LeaseException(ResultCodeEnum.ADMIN_ACCOUNT_NOT_EXIST_ERROR);
        }
        //验证用户是否被禁
        if (systemUser.getStatus() == BaseStatus.DISABLE){
            throw new LeaseException(ResultCodeEnum.ADMIN_ACCOUNT_DISABLED_ERROR);

        }

        //验证密码
        if (systemUser.getPassword().equals(DigestUtil.sha256Hex(loginVo.getPassword()))){
            throw new LeaseException(ResultCodeEnum.ADMIN_ACCOUNT_ERROR);
        }
        return JwtUtils.createToken(systemUser.getId(),systemUser.getUsername());
    }

    @Override
    public SystemUserInfoVo getUserInfo(String accessToken) {
        SystemUserInfoVo systemUserInfoVo = new SystemUserInfoVo();
        //通过token获取当前用户id
        Long  id = JwtUtils.parseToken(accessToken).get("userId",Long.class);
        //根据用户id查询用户姓名跟头像
        SystemUser systemUser = systemUserMapper.selectById(id);

        BeanUtils.copyProperties(systemUser,systemUserInfoVo);
        return systemUserInfoVo;
    }
}
